import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/my/bottom_sheet_widget.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';
import 'package:sui_shou_pai/news/bottom_tool_bar.dart';
import 'package:sui_shou_pai/record/record_comment_list.dart';
import 'package:sui_shou_pai/record/record_entity/photo_record_entity.dart';
import 'package:sui_shou_pai/utils/storage_util.dart';

import 'image_widget.dart';

class RecordDetail extends StatefulWidget {
  PhotoRecordEntity photoRecordEntity;

  RecordDetail({Key key, this.photoRecordEntity}) : super(key: key);

  @override
  _RecordDetailState createState() => _RecordDetailState();
}

class _RecordDetailState extends State<RecordDetail> {
  // void deleteRecord(int id) {
  //   HttpRequest.request(
  //     "$BASE_URL/photo-record/deletePhotoRecord/$id",
  //     method: "POST",
  //   ).then((value) {
  //     setState(() {});
  //   });widget.callback(true);
  // }

  String role;

  initRole() async {
    role = await StorageUtil.getStringItem("role");
    print(role);
  }

  Future<void> deleteRecord(int id) async {
    HttpRequest.request("$BASE_URL/photo-record/deletePhotoRecord/$id",
            method: "POST", token: await StorageUtil.getStringItem("token"))
        .then((value) {
      setState(() {});
    });
  }

  // 根据id修改记录实体状态
  Future<bool> acceptPhotoRecord(PhotoRecordEntity photoRecordEntity) async {
    if (photoRecordEntity.status == "4") {
      HttpRequest.request("$BASE_URL/photo-record/acceptById",
              params: {"id": photoRecordEntity.id},
              method: "GET",
              token: await StorageUtil.getStringItem("token"))
          .then((value) {
        setState(() {
          photoRecordEntity.status = "2";
          //getStatus(photoRecordEntityDetail);
        });
      });
      return true;
    } else {
      return false;
    }
  }

  @override
  void initState() {
    super.initState();
    role = InitInformation.role;
  }

  @override
  Widget build(BuildContext context) {
    List<String> imageSplit(String image) {
      List<String> imageList = image.split(',');
      return imageList;
    }

    String _msgflag = "";
    // PhotoRecordEntity photoRecordEntityDetail =
    //     ModalRoute.of(context).settings.arguments;
    // PhotoRecordEntity globalPhotoRecordEntityDetail =
    //     ModalRoute.of(context).settings.arguments;
    // if (globalPhotoRecordEntityDetail.status.isNotEmpty) {
    //   if (globalPhotoRecordEntityDetail.status == "4") {
    //     photoRecordEntityDetail = globalPhotoRecordEntityDetail;
    //   }
    // }
    print("------detail_id---------" + widget.photoRecordEntity.id.toString());
    List<String> imageList = imageSplit(widget.photoRecordEntity.image);
    //print("-------------" + globalPhotoRecordEntityDetail.status);
    if (widget.photoRecordEntity.status.isNotEmpty) {
      if (widget.photoRecordEntity.status == "4") {
        acceptPhotoRecord(widget.photoRecordEntity);
      }
    }
    Future<bool> approve(String id) async {
      print("---------------id------" + id);
      if (widget.photoRecordEntity.status == "2") {
        _msgflag = "审核成功";
        HttpRequest.request("$BASE_URL/photo-record/approveById",
                params: {"id": id},
                method: "GET",
                token: await StorageUtil.getStringItem("token"))
            .then((value) {
          setState(() {
            widget.photoRecordEntity.status = "1";
            //getStatus(photoRecordEntityDetail);
          });
        });
        return true;
      } else {
        _msgflag = "通过失败，请等待负责人执行";
        return false;
      }
    }
    // print(imageList);
    // print(imageList.length);

    return MaterialApp(
      title: '记录详情页面',
      theme: ThemeData(primaryColor: Colors.white),
      color: Colors.white,
      home: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
              elevation: 0,
              centerTitle: true,
              title: Text('记录详情', style: TextStyle(color: Colors.black)),
              // 自定义返回按钮
              leading: GestureDetector(
                  child: Icon(Icons.arrow_back),
                  onTap: () {
                    Navigator.of(context).pop();
                  }),
              // 设置保存按钮
              actions: <Widget>[
                role == "boss"
                    ? Row(
                        children: <Widget>[
                          IconButton(
                              icon: Icon(Icons.check),
                              onPressed: () {
                                approve(widget.photoRecordEntity.id);
                                Fluttertoast.showToast(
                                    msg: _msgflag,
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.BOTTOM);
                              }),
                          IconButton(
                              icon: Icon(Icons.clear),
                              onPressed: () {
                                showDialog(
                                    barrierDismissible: true, //是否点击空白区域关闭对话框,默认为true，可以关闭
                                    context: context,
                                    // barrierColor: Colors.transparent,
                                    builder: (BuildContext context) {
                                      var list = [];
                                      list.add('确认删除');
                                      return BottomSheetWidget(
                                        list: list,
                                        onItemClickListener: (index) async {
                                          Navigator.pop(context);
                                          if (index == 0) {
                                            int _id = int.parse(widget.photoRecordEntity.id);
                                            String s = "$_id 删除";
                                            print("-----delete--id----");
                                            Navigator.of(context).pop(s);
                                          }
                                        },
                                      );
                                    });

                              }),
                        ],
                      )
                    : SizedBox.shrink()
              ]),
          body: Column(
            children: <Widget>[
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      getStatus(widget.photoRecordEntity),
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 16),
                        child: Text(
                          widget.photoRecordEntity.content,
                          maxLines: 10,
                          style: TextStyle(
                            fontSize: 17,
                          ),
                        ),
                      ),
                      Container(
                        constraints: BoxConstraints(maxHeight: 440),
                        child: ListView.separated(
                          scrollDirection: Axis.horizontal,
                          shrinkWrap: true,
                          itemCount:
                              imageList.length == 0 ? 0 : imageList.length - 1,
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                                margin: EdgeInsets.symmetric(horizontal: 6),
                                height: 300,
                                child: ClipRRect(
                                  borderRadius: borderRadiusAll8(),
                                  child: ImageWidget(
                                      url: imageSplit(widget
                                          .photoRecordEntity.image)[index]),
                                ));
                          },
                          separatorBuilder: (BuildContext context, int index) {
                            return new Divider();
                          },
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 16),
                        padding:
                            EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                        decoration: BoxDecoration(
                            color: greyF6F6F6,
                            borderRadius: borderRadiusAll8()),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 4),
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.perm_identity_outlined,
                                      size: 20.0),
                                  SizedBox(
                                    width: 4.0,
                                  ),
                                  Text(
                                    widget.photoRecordEntity.publisherName,
                                    style: TextStyle(
                                      fontSize: 17,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 4),
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.location_on_outlined, size: 20.0),
                                  SizedBox(
                                    width: 4.0,
                                  ),
                                  Text(
                                    widget.photoRecordEntity.location,
                                    style: TextStyle(
                                      fontSize: 17,
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 4),
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.access_time_rounded, size: 20.0),
                                  SizedBox(
                                    width: 4.0,
                                  ),
                                  Text(
                                    widget.photoRecordEntity.updateTime,
                                    style: TextStyle(fontSize: 17),
                                  ),
                                ],
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 4),
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.alternate_email, size: 20.0),
                                  SizedBox(
                                    width: 4.0,
                                  ),
                                  Text(
                                    widget.photoRecordEntity.responsibleName,
                                    style: TextStyle(
                                      fontSize: 17,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      RecordCommentList(
                        photoRecordId: widget.photoRecordEntity.id,
                      ),
                    ],
                  ),
                ),
              ),
              BottomToolBar(
                  currentContentId: widget.photoRecordEntity.id,
                  currentContentType: "record"),
            ],
          )),
    );
  }

  Widget getStatus(PhotoRecordEntity photoRecordEntity) {
    var statusColor;
    var title;
    if (photoRecordEntity.status.isNotEmpty) {
      if (photoRecordEntity.status == "1") {
        statusColor = Colors.greenAccent;
        title = "已通过";
      } else if (photoRecordEntity.status == "2") {
        statusColor = Colors.yellowAccent;
        title = "执行中";
      } else {
        statusColor = Colors.redAccent;
        title = "已提交";
      }
    }

    return Container(
        alignment: Alignment.center,
        height: 32,
        width: 64,
        decoration:
            BoxDecoration(borderRadius: borderRadiusAll4(), color: statusColor),
        child: Center(
            child: Text(
          title,
          style: TextStyle(color: Colors.black54, fontSize: 16),
        )));
  }
}
